package ua.kpi_java_training5.alekseenko.src.module2;

/**
 * Author: Aleksey Alekseenko
 * Date: 04.06.13
 */
public class Predator extends Fish {

    public Predator() {
        this.eatable = false;
    }

    public Predator(int x, int y) {
        this.position.x = x;
        this.position.y = y;
        this.eatable = false;
    }

    @Override
    /**
     * Выплывает за рамки бассейна,
     */
    public void move(int step) {
        Fish nearestFish = findNearestVictim();
        if (this.position.x >= nearestFish.position.x && this.position.y < nearestFish.position.y) {

            if (this.position.x - nearestFish.position.x > nearestFish.position.y - this.position.y) {
                this.position.x -= step;
            } else {
                this.position.y += step;
            }
        } else if (this.position.x < nearestFish.position.x && this.position.y <= nearestFish.position.y) {
            if (nearestFish.position.x - this.position.x > nearestFish.position.y - this.position.y) {
                this.position.x += step;
            } else {
                this.position.y += step;
            }
        } else if (this.position.x <= nearestFish.position.x && this.position.y > nearestFish.position.y) {
            if (nearestFish.position.x - this.position.x > this.position.y - nearestFish.position.y) {
                this.position.x += step;
            } else {
                this.position.y -= step;
            }
        } else if (this.position.x > nearestFish.position.x && this.position.y >= nearestFish.position.y) {
            if (this.position.x - nearestFish.position.x > this.position.y - nearestFish.position.y) {
                this.position.x -= step;
            } else {
                this.position.y -= step;
            }
        } else {
            System.out.println("I have mistake");
        }
        this.age += 1;
    }

    /**
     * Predator will be move to first nearest victim
     *
     * @return
     */
    private Fish findNearestVictim() {
        double min = Double.MAX_VALUE;
        int nearestVictimIndex = 0;       // выдаст ошибку если не останется жертв
        for (int index = 0; index < fishFactory.victims.size(); index++) {
            if (min > calcMinDistance(fishFactory.victims.get(index).position)) {
                min = calcMinDistance(fishFactory.victims.get(index).position);
                nearestVictimIndex = index;
            }
        }
        return fishFactory.victims.get(nearestVictimIndex);
    }

    /**
     * Calculates min distance
     *
     * @param position
     * @return
     */
    public double calcMinDistance(Position position) {
        return Math.sqrt(Math.abs(this.position.x - position.x) ^ 2 + Math.abs(this.position.y - position.y) ^ 2);
    }

}